package com.mezz.bones.bff.app.adapter.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.mezz.bones.framework.base.domain.response.Result;
import com.mezz.bones.framework.mybatis.dynamic.domain.dto.DynamicDataSourceInfo;
import com.mezz.bones.framework.mybatis.dynamic.service.DynamicDataSourceService;
import com.mezz.bones.framework.mybatis.dynamic.util.DynamicDataSourceHelper;
import com.mezz.bones.user.application.repository.ISysUserRepository;
import com.mezz.bones.user.client.domain.entity.SysUser;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: zhuang
 * @Date: 2024/8/30 19:02
 * @Description: TODO
 * @Version: 1.0
 **/

@RestController
@RequestMapping("/dynamic")
@SaIgnore
@Api("测试项目启动")
@Slf4j
@AllArgsConstructor
public class DynamicDataSourceController {

    private final ISysUserRepository sysUserRepository;
    private final DynamicDataSourceService dynamicDataSourceService;

    @GetMapping("/user/info")
    public Result<SysUser> dynamicGetUser(String userId) {

        DynamicDataSourceHelper.restoreDefaultDataSource();
        SysUser userInfo = sysUserRepository.findByUserId(userId);
        log.info("db1: " + userInfo.getUsername());
        SysUser slaver = sysUserRepository.findByUserIdWithSlaver(userId);
        log.info("db2: " + slaver.getUsername());
        DynamicDataSourceHelper.switchDataSource("db3");

        SysUser userInfoDb3 = sysUserRepository.findByUserId(userId);
        try {
            log.info("db3: " + userInfoDb3.getUsername());

        }finally {
            DynamicDataSourceHelper.restorePreviousDataSource();
        }

        //移除数据源
        dynamicDataSourceService.removeDataSource("db3");

        //再次切换到被移除的数据源
        DynamicDataSourceHelper.switchDataSource("db3");
        userInfoDb3 = sysUserRepository.findByUserId(userId);
        try {
            log.info("db3: " + userInfoDb3.getUsername());

        }finally {
            DynamicDataSourceHelper.restorePreviousDataSource();
        }

        return Result.OK(userInfo);
    }
}
